package org.xin.security.config.handle;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.xin.common.result.Result;
import org.xin.common.result.ResultCode;
import org.xin.common.util.ClientUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> 认证失败处理类 返回未授权 </p>
 * @modified By：$
 * @version: $
 */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        log.error(msg);
        ClientUtil.renderString(response, JSONUtil.toJsonStr(Result.error(ResultCode.UN_LOGIN, msg)));
    }
}
